package pinkblob.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import pinkblob.event.DatabaseFileHandler;

@SuppressWarnings("unchecked")
public class Upload extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pid = null, render = null;
		
		pid = request.getParameter("pid");
		render = request.getParameter("render");
		
		System.out.println("==============PARAMETER: ProjectID:" + pid + " Render: " + render + "==========");		
		System.out.println("==================TRYING TO RENDER UPLOAD PAGE=================================");
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		if("true".equals(render) && Integer.parseInt(pid)!= 0) {
					
		out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"de\" lang=\"de\">");
		out.println("	<body>");
	    out.println("		<form enctype=\"multipart/form-data\" action=\"http://localhost:8080/PinkBlob/upload/\" method=\"post\">");
	    out.println("			File to process: <input name=\"userfile\" type=\"file\">");
	    out.println("			<input type=\"hidden\" name=\"pid\" value=\""+ pid + "\">");
	    out.println("			<input type=\"submit\" value=\"Send File\">");	
	    out.println("		</form>");	
		out.println("   </body>");
		out.println("</html>");
		} else
			out.println("<html><body>Parameter error!</body></html>");
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
				System.out.println("=========================TRYING TO UPLOAD=======================================");
			
				// Check that we have a file upload request
				boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			
				if(isMultipart){
					
					response.setContentType("text/html");
					PrintWriter out = response.getWriter();	
					
					// Create a factory for disk-based file items
					FileItemFactory factory = new DiskFileItemFactory();
					// Create a new file upload handler
					ServletFileUpload upload = new ServletFileUpload(factory);
					// Parse the request
					List items = null;
					try{
						/* FileItem */ items = upload.parseRequest(request);
					}catch(FileUploadException e){
						out.println("<html><body>FileUploadException!</body></html>");
						System.out.println("----------Upload.java: FileUploadException----------");
						e.printStackTrace();
					}
					
					// Process the uploaded items
					Iterator iterFields = items.iterator();
					Map<String, String> paramMap = new HashMap<String, String>();
										
					while(iterFields.hasNext()) {
						FileItem item = (FileItem) iterFields.next();
						
						// Parse for parameters
						if(item.isFormField()) {
							String param = item.getFieldName();
					        String value = item.getString();
					        
					        paramMap.put(param, value);
						}
					}
					
					Iterator iter = items.iterator();										
										
					while (iter.hasNext()) {
						
					    FileItem item = (FileItem) iter.next();
					    
					    // Process a file upload
					    if(!item.isFormField()) {
					    						   				    		
					        String fileName = item.getName();					        					        					      					       					       					        
					        
					        // Write to database					        
					        DatabaseFileHandler handler = new DatabaseFileHandler();
					        
					        try{
					        	handler.saveFile(Integer.parseInt(paramMap.get("pid")), item.getName(), new Date().getTime(), item.get());
					        }catch(Exception e){
					        	out.println("<html><body>Could not save file in database!</body></html>");
					        	System.out.println("----------Upload.java: Could not save file in database!----------");
					        	e.printStackTrace();
					        }
					        
					        out.println("<html><body>File written to database!</body></html>");
					        System.out.println("=========================WRITTEN TO DATABASE=================================");
					    }
					}
						
				}else{
					response.setContentType("text/html");
					PrintWriter out = response.getWriter();					
					out.println("<html><body>Request is not Multipart!</body></html>");
				}
			}
}	